'use strict';

export default app => {
  const mongoose = app.mongoose;
  const Schema = mongoose.Schema;

  const templatePage = new Schema({
    /**
    * 数据键值
    */
    name: { type: String, default: '', index: true, unique: true },
    /**
     * 创建时间
     */
    createTime: { type: Date, default: new Date() },
    /**
     * 路径
     */
    path: { type: String, default: '', index: true, unique: true  },
    /**
     * 描述
     */
    description: { type: String, default: '' },
  });

  /**
   * 获取所有数据
   */
  templatePage.statics.findAll = function() {
    return this.find();
  };

  /**
   * 更新数据
   */
  templatePage.statics.updateWithId = function(id, upData) {
    return this.updateOne({ 
      _id: mongoose.Types.ObjectId(id)
    }, upData);
  };

  /**
   * 根据参数获取数据
   */
  templatePage.statics.findWithQuery = function(query) {
    const newQuery = { ...query }
    if (newQuery._id) {
      newQuery._id = mongoose.Types.ObjectId(newQuery._id)
    }
    return this.findOne(query)
  };

  /**
   * 获取个数
   */
  templatePage.statics.findCount = function(query) {
    return this.countDocuments(query);
  };
  
  // 删除数据
  templatePage.statics.removeWithId = async function(id) {
    return this.deleteOne({
      _id: mongoose.Types.ObjectId(id),
    });
  };

  return mongoose.model('TemplatePage', templatePage, 'templatePages');
};